package cn.com.xiaoshoujia.activities.activity;

import cn.com.xiaoshoujia.activities.dto.*;
import cn.com.xiaoshoujia.activities.mapper.ActivityMapper;
import cn.com.xiaoshoujia.activities.mapper.ActivityRulesMapper;
import cn.com.xiaoshoujia.order.entity.ActivityOrder;
import cn.com.xiaoshoujia.order.mapper.ActivityOrderMapper;
import cn.com.xiaoshoujia.user.mapper.ActivityCluesMapper;
import cn.com.xiaoshoujia.user.mapper.ActivityJoinMapper;
import cn.com.xiaoshoujia.user.mapper.ActivityTeamHeadMapper;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author dulei
 * @Title: ActivityJoinActivity
 * @Description: 团购人员activity
 * @Time 2017/7/30 20:14
 */
@Repository
public class ActivitiesJoinActivity {

    Logger logger = LoggerFactory.getLogger(ActivitiesJoinActivity.class);

    @Autowired
    ActivityJoinMapper activityJoinMapper;

    @Autowired
    ActivityTeamHeadMapper activityTeamHeadMapper;

    @Autowired
    ActivityCluesMapper activityCluesMapper;

    @Autowired
    ActivityMapper activityMapper;

    @Autowired
    ActivityOrderMapper activityOrderMapper;

    @Autowired
    ActivityRulesMapper activityRulesMapper;

    /**
     * @Author: dulei
     * @Description: 团购活动订单详情
     * @param:  headId 团ID id 团购活动ID
     * @Date: 2017/7/31 11:24
     */
    public ActivityJoinResultDTO findTeamJoin(Long headId, Long id) throws UnsupportedEncodingException {
        ActivityJoinResultDTO activityJoinResultDTO = new ActivityJoinResultDTO();
        activityJoinResultDTO.setId(id);

        logger.debug("获得拼团信息");
        ActivityHeadDTO teamHeadRule = (ActivityHeadDTO) activityTeamHeadMapper.findTeamHeadRule(headId);
        if (null!=teamHeadRule){
            BeanUtils.copyProperties(teamHeadRule,activityJoinResultDTO);
            logger.debug("团长姓名解码");
            activityJoinResultDTO.setSysName(URLDecoder.decode(activityJoinResultDTO.getSysName(),"utf-8"));
        }
        logger.debug("获得拼团成员信息");
        List<ActivityJoinDetailDTO> teamJoin = activityJoinMapper.findTeamJoin(headId, id);
        if (null!=teamJoin && teamJoin.size()>0){
            BigDecimal bigDecimal = new BigDecimal(0);
            for (ActivityJoinDetailDTO activityJoin : teamJoin) {
                if (activityJoin.getStatus().intValue()==1)
                    bigDecimal = bigDecimal.add(activityJoin.getPrice());
                bigDecimal = bigDecimal.subtract(activityJoin.getRefundAmount());
                //表单报名姓名进行解码
                logger.debug("成员名称解码");
                activityJoin.setUserName(URLDecoder.decode(activityJoin.getUserName(),"utf-8"));
            }
            activityJoinResultDTO.setCount(teamJoin.size());
            activityJoinResultDTO.setAmount(bigDecimal);
            activityJoinResultDTO.setJoins(teamJoin);
        }
        return  activityJoinResultDTO;
    }

    /**
     * @Author: dulei
     * @Description: 查询用户报名手机号
     * @param:  clueId 报名表单ID
     * @Date: 2017/7/31 14:35
     */
    public String findCluesPhone(Long clueId) {
        return activityCluesMapper.findCluePhoneById(clueId);
    }
    /**
     * @Author: dulei
     * @Description: 查看用户购买详情信息
     * @param: clueId 用户表单Id
     * @Date: 2017/7/31 15:34
     */
    public ActivityCluesDetailDTO findDetail(Long clueId) throws UnsupportedEncodingException {
        ActivityCluesDetailDTO detail = (ActivityCluesDetailDTO) activityCluesMapper.findDetail(clueId);
        detail.setUserName(URLDecoder.decode(detail.getUserName(),"utf-8"));
        detail.setValueJson(URLDecoder.decode(detail.getValueJson(),"utf-8"));
        return detail;
    }
    /*--------------------wx start--------------------*/
    /**
     * @Author: dulei
     * @Description: 查询用户的团信息
     * @Date: 2017/8/3 18:48
     */
    public ActivityUserTeamDTO findUserJoin(String sysId, Long id) throws UnsupportedEncodingException,RuntimeException {
        ActivityUserTeamDTO userTeamDTO = new ActivityUserTeamDTO();
        logger.info("userTeam message");
        Long teamId = activityOrderMapper.findJoinNoPay(sysId,id);
        ActivityUserTeamDTO userTeam = null;
        if (null != teamId){
            logger.info("no pay team");
            userTeam = (ActivityUserTeamDTO) activityJoinMapper.findNoPayTeam(sysId,id,teamId);
        }else{
            try {
                logger.info("find no fail team");
                userTeam = (ActivityUserTeamDTO) activityJoinMapper.findNoFailTeam(sysId,id);
            }catch (Exception e){
                throw new RuntimeException("find no fail team exception");
            }

            if (null==userTeam){
                logger.info("get new team");
                userTeam = (ActivityUserTeamDTO) activityJoinMapper.findUserJoin(sysId,id);
            }
        }

        if (null!=userTeam){
            BeanUtils.copyProperties(userTeam,userTeamDTO);
            if (userTeam.getJoinType().intValue()==1 && (userTeam.getOrderStatus().intValue()==-1 ||userTeam.getOrderStatus().intValue()==0)){
                userTeamDTO.setJoinStatus(null);
            }
            logger.info("userName utf-8");
            userTeamDTO.setUserName(URLDecoder.decode(userTeamDTO.getUserName(),"utf-8"));
            logger.info("joinUser imageUrl");
            List userUrl = activityJoinMapper.findJoinUrl(userTeam.getHeadId(),id);
            userTeamDTO.setImgUrl(userUrl);
            userTeamDTO.setCount(userUrl.size());
            logger.info("get timeLimit");
            Integer timeLimit = activityRulesMapper.finByActivityId(id);
            userTeamDTO.setEndTime(null==userTeamDTO.getCreateTime()?null:DateUtils.addHours(userTeamDTO.getCreateTime(),timeLimit));
        }
        ActivityOrder activityOrder = activityOrderMapper.findSingleStatus(sysId, id);
        if (null!=activityOrder){
            userTeamDTO.setSingleStatus(activityOrder.getStatus());
            userTeamDTO.setSingleOrderId(activityOrder.getOrderId());
        }
        return userTeamDTO;
    }

    /**
     * @param wxParamDTO
     * @Author: dulei
     * @Description: 查询分享者团信息
     * @Date: 2017/8/3 18:48
     * @param wxParamDTO
     */
    public ActivityShareTeamDTO shareJoin(ActivityWxParamDTO wxParamDTO) throws UnsupportedEncodingException {
        logger.info("shareId message");
        ActivityShareTeamDTO shareTeamDTO = new ActivityShareTeamDTO();
        logger.info("shareTeam message");
        ActivityShareTeamDTO shareTeam = (ActivityShareTeamDTO) activityJoinMapper.findShareJoin(wxParamDTO.getHeadId());
        if (null!=shareTeam){
            BeanUtils.copyProperties(shareTeam,shareTeamDTO);
            logger.info("headName utf-8");
            shareTeamDTO.setHeadName(URLDecoder.decode(shareTeam.getHeadName(),"utf-8"));
            logger.info("joinUser imageUrl");
            shareTeamDTO.setImgUrl(activityJoinMapper.findJoinUrl(wxParamDTO.getHeadId(),wxParamDTO.getId()));
            logger.info("get user shareName");
            shareTeamDTO.setShareName(URLDecoder.decode(activityJoinMapper.findShareName(wxParamDTO.getSysId()),"utf-8"));
            logger.info("get timeLimit");
            Integer timeLimit = activityRulesMapper.finByActivityId(wxParamDTO.getId());
            shareTeamDTO.setEndTime(DateUtils.addHours(shareTeam.getCreateTime(),timeLimit));
        }
        return shareTeamDTO;
    }

    /**
     * @Author: dulei
     * @Description: 单买未支付，显示信息
     * @param:  sysId 用户唯一编码 id 活动ID
     * @Date: 2017/8/5 15:41
     */
    public ActivityOrderJoinDTO teamNoPay(String sysId, Long id, Integer type) {
        return (ActivityOrderJoinDTO) activityOrderMapper.teamNoPay(sysId,id,type);
    }

    public ActivityCluesMsgDTO findUserMsg(Long clueId) {
        return (ActivityCluesMsgDTO) activityCluesMapper.findPhoneByClueId(clueId);
    }

    public ActivitiesCluesRemarkDTO findRemark(Long id) {
        Object ob =  activityCluesMapper.findRemark(id);
        if (ob==null){
            return null;
        }
        ActivitiesCluesRemarkDTO activitiesCluesRemarkDTO = (ActivitiesCluesRemarkDTO) ob;
        try {
            activitiesCluesRemarkDTO.setUserName( URLDecoder.decode(activitiesCluesRemarkDTO.getUserName(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("user name error ， cules id is {}", id);
            return null;
        }
        return activitiesCluesRemarkDTO;
    }

    public boolean updateRemark(Long id, String remark) {
        return activityCluesMapper.updateRemark( id, remark)==1?true:false;
    }

    public boolean changeVolumeStatus(Long id, Integer status) {
        return activityCluesMapper.changeVolumeStatus( id, status)==1?true:false;
    }
    /*--------------------wx end----------------------*/
}
